<!-- 营业收入管理 -->
<script lang="ts" setup>
import {
  listOperatingRevenue,
  delOperatingRevenue,
  addOperatingRevenue,
  putOperatingRevenue,
} from "@/api/RevenueManagement";
import { globalHeaders } from "@/utils/request";
import { ElMessageBox, ElUpload , ElMessage } from "element-plus";
import { deptTreeSelect } from "@/api/role";
import { onMounted, getCurrentInstance, ref, reactive, toRefs } from "vue";
let dateRange = ref();
let canUpload = ref(false);
let isDialogVisible = ref(false);
const total = ref(0);
const loading = ref(true);
const { proxy } = getCurrentInstance();
const uploadRef = ref();
const checkedRows = ref([]);
const checkAll = ref(false);
const isIndeterminate = ref(true);

let entryNameItems = [
  { label: "招投标服务费", value: "1" },
  { label: "标书收入", value: "2" },
  { label: "咨询费", value: "3" },
  { label: "其他费用", value: "4" },
];
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    revenueType: null,
    amountStart: "",
    amountEnd: "",
    amount: "",
    businessTime: "",
    params: {
      businessTime: undefined,
    },
  },
});
let departmentItems = ref([]);;
const { queryParams } = toRefs(data);
let headers = [
  { title: "", key: "checkedItem", sortable: false },
  { title: "部门", sortable: false, key: "deptName" },
  { title: "项目名称", sortable: false, key: "revenueTypeC" },
  { title: "日期", sortable: false, key: "businessTime" },
  { title: "金额", sortable: false, key: "amount" },
  { title: "操作", key: "actions", sortable: false },
];
let Data = ref([]);
/*** 营业收入管理导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url:
    import.meta.env.VITE_APP_BASE_API + "/system/operatingRevenue/importData",
});
/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await deptTreeSelect();
  departmentItems.value = res.data;
};

//重置按钮操作
const Resetting = () => {
  dateRange.value = "";
  queryParams.value.revenueType = null;
  queryParams.value.amountStart = "";
  queryParams.value.deptId = '';
  queryParams.value.amountEnd = "";
  getList();
};
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRange.value, "BusinessTime");
  const res = await listOperatingRevenue(queryParams.value);
  Data.value = res.rows;
  Data.value.forEach((element, index) => {
    element.id = index + 1;
    switch (element.revenueType) {
      case "1":
        element.revenueTypeC = "招投标服务费";
        break;
      case "2":
        element.revenueTypeC = "标书收入";
        break;
      case "3":
        element.revenueTypeC = "咨询费";
        break;
      case "4":
        element.revenueTypeC = "其他费用";
        break;
    }
  });
  total.value = res.total;
  loading.value = false;
};
//新增弹框
let addOoperate = ref("");
const handleAdd = (text) => {
  isDialogVisible.value = true;
  addOoperate.value = text;
};
//保存按钮
const handleSave = async () => {
  if (addOoperate.value === "add") {
    let res = await addOperatingRevenue(queryParams.value);
  }
  if (addOoperate.value === "operate") {
    let res = await putOperatingRevenue(queryParams.value);
  }
  addOoperate.value = "";
  queryParams.value.revenueType = null;
  queryParams.value.businessTime = "";
  queryParams.value.deptId = null;
  queryParams.value.amount = "";
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;

  getList();
  isDialogVisible.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 操作修改按钮 */
const editItem = (item) => {
  isDialogVisible.value = true;
  addOoperate.value = "operate";
  queryParams.value = { ...item };
};

//关闭弹窗
const closeDialog = () => {
  isDialogVisible.value = false;
  addOoperate.value = "";
  queryParams.value.revenueType = null;
  queryParams.value.businessTime = "";
  queryParams.value.deptId = null;
  queryParams.value.amount = "";
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
};
/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download(
    "system/operatingRevenue/importTemplate",
    {},
    `operatingRevenue_template_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = "营业收入管理导入";
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    {
      dangerouslyUseHTMLString: true,
    }
  );

  getList();
};

/** 提交上传文件 */
const submitFileForm = () => {
  if (canUpload.value) {
    uploadRef.value?.submit();
  }else{
    ElMessage.error("请先选择文件");
  }
};
const handleRemove = (e) => {
  canUpload.value = false
}
const handleFileChange = (fileList) => {
  canUpload.value = fileList? true : false;
};
const onSelectionChange = (e) => {};
/**
 * 删除营业收入管理数据项
 *
 * @param row 营业收入管理数据项对象
 * @returns 无返回值，执行删除操作后更新列表
 */
const handleDelete = async (row) => {
  const _operatingRevenueIds = row.operatingRevenueId;
  await proxy?.$modal
    .confirm(
      '是否确认删除营业收入管理编号为"' + _operatingRevenueIds + '"的数据项？'
    )
    .finally(() => (loading.value = false));
  await delOperatingRevenue(_operatingRevenueIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};
const handleCheckAllChange = (val) => {
  if (val) {
    checkedRows.value = Data.value.map((item) => item.operatingRevenueId);
  } else {
    checkedRows.value = [];
  }
  isIndeterminate.value = false;
};
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === Data.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < Data.value.length;
};
const handleDeleteAll = async () => {
  const _operatingRevenueIds = checkedRows.value;
  await proxy?.$modal
    .confirm("是否确认删除选中的所有数据项？")
    .finally(() => (loading.value = false));
  await delOperatingRevenue(_operatingRevenueIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};
const handleSizeChange = (e) => {
  queryParams.value.pageSize = e;
  getList();
};
const handleCurrentChange = (w) => {
  getList();
};
onMounted(() => {
  getList();
  getTreeSelect();
});
</script>

<template>
  <VCard>
    <VCardText class="py-10">
      <VRow class="match-height">
        <VCol cols="12" md="3">
          <AppSelect
            :items="entryNameItems"
            item-title="label"
            item-value="value"
            v-model="queryParams.revenueType"
            label="项目名称"
            placeholder="请选择项目名称"
            density="compact"
          />
        </VCol>
        <VCol cols="12" md="3">
          <div>
            <div>
              <span class="demonstration">公司</span>
            </div>
            <el-tree-select
              class="custom-tree-select"
              v-model="queryParams.deptId"
              :data="departmentItems"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children',
              }"
              value-key="id"
              placeholder="请选择公司"
              check-strictly
            />
          </div>
        </VCol>
        <VCol cols="12" md="3">
          <div class="block">
            <div>
              <span class="demonstration">交易时间区间</span>
            </div>
            <el-date-picker
              style="
                background-color: rgb(var(--v-theme-surface));
                inline-size: 100%;
              "
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </div>
        </VCol>

        <VCol cols="12" md="3">
          <VRow class="match-height">
            <VCol cols="12" md="5">
              <AppTextField
                v-model="queryParams.amountStart"
                label="金额区间"
                placeholder="请输入金额"
                type="number"
                density="compact"
              />
            </VCol>

            <div class="display_flex-end" style="padding-block-end: 15px">
              ～
            </div>

            <VCol cols="12" md="5">
              <AppTextField
                v-model="queryParams.amountEnd"
                label=" "
                placeholder="请输入金额"
                type="number"
                density="compact"
              />
            </VCol>
          </VRow>
        </VCol>

        <VCol cols="12" md="3" class="display_flex-end">
          <VBtn color="primary" density="compact" @click="handleQuery">
            查询
          </VBtn>
          <VBtn variant="outlined" density="compact" @click="Resetting">
            重置
          </VBtn>
        </VCol>
        <VCol cols="12" md="3" class="display_flex-end">
          <VBtn color="primary" density="compact" @click="handleAdd('add')">
            新增
          </VBtn>
          <VBtn color="primary" density="compact" @click="handleImport">
            导入
          </VBtn>
          <VBtn color="error" density="compact" @click="handleDeleteAll">
            删除
          </VBtn>
        </VCol>

        <VCol cols="12" md="12">
          <div style="position: relative">
            <el-checkbox
              class="checkboxiii"
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedRows"
              @change="handleCheckedCitiesChange"
            >
              <VDataTable
                :headers="headers"
                :items="Data"
                :items-per-page="queryParams.pageSize"
                :page="queryParams.pageNum"
                class="text-no-wrap"
                item-key="id"
              >
                <template #item.checkedItem="{ item }">
                  <div class="d-flex gap-1 position_a">
                    <el-checkbox
                      :key="item.id"
                      :value="item.operatingRevenueId"
                      v-model="item.isChecked"
                    >
                    </el-checkbox>
                  </div>
                </template>

                <template #item.actions="{ item }">
                  <div class="d-flex gap-1 position_a">
                    <IconBtn @click="editItem(item)">
                      <VIcon>
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          class="icon icon-tabler icon-tabler-edit"
                          width="20"
                          height="20"
                          viewBox="0 0 24 24"
                          stroke-width="1.5"
                          stroke="rgb(var(--v-theme-primary))"
                          fill="none"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                        >
                          <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                          <path
                            d="M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1"
                          />
                          <path
                            d="M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415z"
                          />
                          <path d="M16 5l3 3" />
                        </svg>
                      </VIcon>
                    </IconBtn>
                    <IconBtn @click="handleDelete(item)">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="icon icon-tabler icon-tabler-trash"
                        width="20"
                        height="20"
                        viewBox="0 0 24 24"
                        stroke-width="1.5"
                        stroke="rgb(var(--v-theme-primary))"
                        fill="none"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      >
                        <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                        <path d="M4 7l16 0" />
                        <path d="M10 11l0 6" />
                        <path d="M14 11l0 6" />
                        <path
                          d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"
                        />
                        <path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3" />
                      </svg>
                    </IconBtn>
                  </div>
                </template>
              </VDataTable>
              <div class="mypagination">
                <el-pagination
                  v-model:current-page="queryParams.pageNum"
                  v-model:page-size="queryParams.pageSize"
                  :page-sizes="[10, 25, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-checkbox-group>
          </div>
        </VCol>

        <VDialog v-model="isDialogVisible" width="800">
          <!-- Dialog close btn -->
          <DialogCloseBtn @click="closeDialog" />

          <!-- Dialog Content -->
          <VCard title="编辑">
            <VCardText>
              <VRow class="match-height">
                <VCol cols="12" md="6">
                  <AppSelect
                    :items="entryNameItems"
                    item-title="label"
                    item-value="value"
                    v-model="queryParams.revenueType"
                    label="项目名称"
                    placeholder="请选择项目名称"
                    density="compact"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <div class="block">
                    <div>
                      <span class="demonstration">交易时间</span>
                    </div>
                    <el-date-picker
                      class="custom-date-picker"
                      style="inline-size: 100%"
                      clearable
                      v-model="queryParams.businessTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      placeholder="请选择时间"
                    >
                    </el-date-picker>
                  </div>
                </VCol>
                <VCol cols="12" md="6">
                  <AppTextField
                    v-model="queryParams.amount"
                    label="收入金额"
                    placeholder="请输入收入金额"
                    density="compact"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <div>
                    <div>
                      <span>部门</span>
                    </div>
                    <el-tree-select
                      class="custom-tree-select"
                      v-model="queryParams.deptId"
                      :data="departmentItems"
                      :props="{
                        value: 'id',
                        label: 'label',
                        children: 'children',
                      }"
                      value-key="id"
                      placeholder="请选择部门"
                      check-strictly
                    />
                  </div>
                </VCol>
              </VRow>
            </VCardText>

            <VCardText class="d-flex justify-end">
              <VBtn @click="handleSave()"> 保存 </VBtn>
            </VCardText>
          </VCard>
        </VDialog>
        <!-- 营业收入管理导入对话框 -->
        <el-dialog
          v-model="upload.open"
          :title="upload.title"
          width="400px"
          append-to-body
        >
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            :on-remove="handleRemove"
            @change="handleFileChange"
            drag
          >
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="text-center el-upload__tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; vertical-align: baseline"
                  @click="importTemplate"
                  >下载模板</el-link
                >
              </div>
            </template>
          </el-upload>
          
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm"
                >确 定</el-button
              >
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </VRow>
    </VCardText>
  </VCard>
</template>

<style lang="scss" >
.display_flex-end {
  display: flex;
  align-items: flex-end;
  gap: 15px;
}

.mb-1 {
  margin-block-end: 0 !important;
}

.el-popper.is-pure {
  z-index: 9999 !important;
}

.el-picker-panel {
  background-color: rgb(var(--v-theme-surface)) !important;
}

.custom-date-picker {
  background-color: rgb(var(--v-theme-surface));
  inline-size: 100%;
}

.el-input__wrapper {
  background-color: rgb(var(--v-theme-surface)) !important;
}

.el-picker-panel__footer {
  background-color: rgb(var(--v-theme-surface)) !important;
}

.el-select__wrapper {
  background-color: rgb(var(--v-theme-surface)) !important;
}

.checkboxiii {
  position: absolute;
  top: 10px;
  left: 20px;
}

.demonstration {
  color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
  font-size: 13px;
}
</style>
